package me.sealer.ssm.service.impl;

import com.github.pagehelper.PageHelper;
import me.sealer.ssm.constant.PageConstant;
import me.sealer.ssm.mapper.ChinaAreaMapper;
import me.sealer.ssm.model.ChinaArea;
import me.sealer.ssm.model.ChinaAreaExample;
import me.sealer.ssm.page.PageResult;
import me.sealer.ssm.service.ChinaAreaService;
import me.sealer.ssm.utils.PageUtil;
import me.sealer.ssm.utils.StringUtil;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 功能描述： $ ChinaAreaServiceImpl
 *
 * @author sealer
 * @email 1178884049@qq.com
 * @date 2019年11月15日 13时50分18秒
 */
@Service
public class ChinaAreaServiceImpl implements ChinaAreaService {
    private final ChinaAreaMapper chinaAreaMapper;

    public ChinaAreaServiceImpl(ChinaAreaMapper chinaAreaMapper) {
        this.chinaAreaMapper = chinaAreaMapper;
    }

    @Override
    public PageResult<ChinaArea> queryAreasPage(String name, Integer level, Integer zipCode, String cityCode, Long code, Long parentCode, int pageNo, int pageSize) {
        ChinaAreaExample example = genExampleIfNonNull(name, level, zipCode, cityCode, code, parentCode);

        pageSize = Math.min(pageSize, PageConstant.MAX_PAGE_SIZE);

        // count
        int count = chinaAreaMapper.countByExample(example);

        // 分页
        PageHelper.startPage(pageNo, pageSize);
        List<ChinaArea> chinaAreaList = chinaAreaMapper.selectByExample(example);

        return PageUtil.generatePageResult(pageNo, pageSize, chinaAreaList, count);
    }

    @Override
    public List<ChinaArea> queryAreas(int level, long parentCode) {
        ChinaAreaExample example = new ChinaAreaExample();
        example.setOrderByClause(" pinyin asc");
        example.createCriteria()
                .andLevelEqualTo(level)
                .andParentCodeEqualTo(parentCode);

        return chinaAreaMapper.selectByExample(example);
    }

    private ChinaAreaExample genExampleIfNonNull(String name, Integer level, Integer zipCode, String cityCode, Long code, Long parentCode) {
        ChinaAreaExample example = new ChinaAreaExample();

        ChinaAreaExample.Criteria criteria = example.createCriteria();

        if (!StringUtil.isNullOrEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        }

        if (Objects.nonNull(level)) {
            criteria.andLevelEqualTo(level);
        }

        if (Objects.nonNull(zipCode)) {
            criteria.andZipCodeEqualTo(zipCode);
        }

        if (cityCode != null && !"".equals(cityCode)) {
            criteria.andCityCodeEqualTo(cityCode);
        }

        if (Objects.nonNull(code)) {
            criteria.andCodeEqualTo(code);
        }

        if (Objects.nonNull(parentCode)) {
            criteria.andParentCodeEqualTo(parentCode);
        }

        return example;
    }
}
